<?php

namespace app\base\command;


use app\base\model\RedianData;
use app\base\model\RedianTask;
use app\base\service\TaskService;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
/**
 * 小甲鱼视频模板预览图下载到服务器任务
 * Class SmsNum
 * @package app\common\command
 */
class XiaojiayuVideoPicDownload extends Command
{
    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xbase:XiaojiayuVideoPicDownload');
        $this->setDescription('XiaojiayuVideoPicDownload');
    }

    protected function execute(Input $input, Output $output)
    {
        $data = $this->app->db->name("ai_voice")->where(['type'=>2,'status'=>1,'is_download'=>0])->select()->toArray();
        $picDir = $this->app->getRootPath() . "public/upload/video_temp/pic";
        if (!is_dir($picDir)) {
            mkdir($picDir, 0755, true);
        }
        foreach ($data as $item){
            $other_data = json_decode($item['other_data'],true);
            if($item['platform_name']=="小甲鱼"){
                $pic_url = $other_data['coverUrl'];
                // 提取文件后缀名称（核心逻辑）
                $extension = $this->extractExtensionFromUrl($pic_url);

                // 使用后缀名构建完整保存路径
                $filename = md5($item['id']) . '.' . ($extension ?: 'jpg'); // 默认jpg
                $savePath = $picDir . '/' . $filename;

                // 下载图片并更新数据库
                try {
                    $this->downloadImage($pic_url, $savePath);
                    $host_pic_url =  "http://dev.blueant.pro/upload/video_temp/pic/{$filename}";
                    $this->app->db->name("ai_voice")
                        ->where('id', $item['id'])
                        ->update([
                            'is_download' => 1,
                            'pic_url' => $host_pic_url
                        ]);

                    $output->info("下载成功: {$item['id']} 后缀: {$extension}");

                } catch (\Exception $e) {
                    $this->app->db->name("ai_voice")
                        ->where('id', $item['id'])
                        ->update([
                            'is_download' => 1,
                        ]);
                    $output->info("下载失败: {$item['id']} - {$e->getMessage()}");
                }

            }
        }
        $this->setQueueSuccess("任务完成");

    }

    /**
     * 下载图片到本地
     */
    private function downloadImage(string $url, string $savePath): void
    {
        $content = file_get_contents($url);
        if ($content === false) {
            throw new \Exception("图片下载失败");
        }

        if (file_put_contents($savePath, $content) === false) {
            throw new \Exception("图片保存失败");
        }
    }


    /**
     * 从URL解析文件后缀名
     */
    private function extractExtensionFromUrl(string $url): string
    {
        // 方法1：直接从URL路径解析（高效）
        $path = parse_url($url, PHP_URL_PATH);
        if ($path && ($ext = pathinfo($path, PATHINFO_EXTENSION))) {
            return strtolower($ext);
        }

        // 方法2：正则匹配（更灵活）
        if (preg_match('/\.([a-z0-9]{2,5})(?:[\?#]|$)/i', $url, $matches)) {
            return strtolower($matches[1]);
        }

        // 方法3：备用方案 - 从文件名部分解析
        $parts = explode('/', $url);
        $filename = end($parts);
        if (($pos = strrpos($filename, '.')) !== false) {
            return strtolower(substr($filename, $pos + 1));
        }

        // 默认返回jpg
        return 'jpg';
    }



}
